<template>
  <div class="exam-result-container">
    <!-- 结果概览 -->
    <div class="result-overview">
      <div class="result-header">
        <h2>{{ exam?.title || '考试结果' }}</h2>
        <div class="result-status">
          <el-tag 
            :type="record?.passStatus === 'PASSED' ? 'success' : 'danger'" 
            size="large"
          >
            {{ record?.passStatus === 'PASSED' ? '通过' : '未通过' }}
          </el-tag>
        </div>
      </div>

      <div class="result-stats">
        <div class="stat-item big">
          <svg :width="120" :height="120" viewBox="0 0 36 36" class="radial">
            <path class="bg" d="M18 2 a 16 16 0 0 1 0 32 a 16 16 0 0 1 0 -32" />
            <path class="bar" :stroke-dasharray="`${correctRate} , 100`" d="M18 2 a 16 16 0 0 1 0 32 a 16 16 0 0 1 0 -32" :class="{ good: correctRate>=85, pass: correctRate>=60 && correctRate<85, fail: correctRate<60 }" />
            <text x="18" y="20.5" class="label">{{ correctRate }}%</text>
          </svg>
          <div class="stat-label">正确率</div>
        </div>
        <div class="stat-item"><div class="stat-value">{{ record?.totalScore ?? 0 }}</div><div class="stat-label">得分</div></div>
        <div class="stat-item"><div class="stat-value">{{ record?.totalPoints ?? 0 }}</div><div class="stat-label">总分</div></div>
        <div class="stat-item"><div class="stat-value">{{ exam?.passScore ?? '-' }}</div><div class="stat-label">及格线</div></div>
        <div class="stat-item"><div class="stat-value">{{ formatDuration(record?.timeSpent) }}</div><div class="stat-label">用时</div></div>
      </div>
    </div>

    <!-- 答题详情 -->
    <div class="answer-details" v-if="exam?.showCorrectAnswers && answers.length > 0">
      <h3>答题详情</h3>
      <div 
        v-for="(answer, index) in answers" 
        :key="answer.id"
        class="answer-item"
      >
        <div class="question-info">
          <div class="question-header">
            <span class="question-number">第 {{ index + 1 }} 题</span>
            <div class="question-meta">
              <el-tag size="small">{{ answer.score }}分</el-tag>
              <el-tag 
                :type="answer.isCorrect ? 'success' : 'danger'" 
                size="small"
              >
                {{ answer.isCorrect ? '正确' : '错误' }}
              </el-tag>
            </div>
          </div>
          <div class="question-content" v-html="answer.question?.content"></div>
        </div>

        <div class="answer-content">
          <div class="user-answer">
            <strong>您的答案：</strong>
            <span :class="{ correct: answer.isCorrect, incorrect: !answer.isCorrect }">
              {{ formatAnswer(answer.userAnswer, answer.question?.questionType, answer.question?.options) }}
            </span>
          </div>
          
          <div v-if="!answer.isCorrect" class="correct-answer">
            <strong>正确答案：</strong>
            <span class="correct">
              {{ formatAnswer(answer.question?.correctAnswers, answer.question?.questionType, answer.question?.options) }}
            </span>
          </div>

          <div v-if="answer.question?.explanation" class="explanation">
            <strong>解析：</strong>
            <p>{{ answer.question.explanation }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 无答案提示 -->
    <div v-else class="no-answers">
      <el-empty description="教师未开启答案展示或暂无答案可显示">
        <el-button type="primary" @click="retakeExam" v-if="canRetake">再次参加</el-button>
        <el-button @click="goBack" style="margin-left: 8px;">返回课程</el-button>
      </el-empty>
    </div>

    <!-- 证书信息 -->
    <div v-if="record?.passStatus === 'PASSED'" class="certificate-section">
      <div class="certificate-info">
        <el-icon class="certificate-icon"><Trophy /></el-icon>
        <h3>恭喜您通过考试！</h3>
        <p>您的证书正在生成中，请稍后在"我的证书"中查看。</p>
        <el-button type="primary" @click="goToCertificates">查看我的证书</el-button>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="result-actions">
      <el-button @click="goBack">返回课程</el-button>
      <el-button 
        v-if="canRetake" 
        type="primary" 
        @click="retakeExam"
      >
        重新考试
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getErrorMessage } from '@/api/http'
import { Trophy } from '@element-plus/icons-vue'
import { examApi } from '@/api/exam'

const route = useRoute()
const router = useRouter()
const recordId = Number(route.params.id)

// 响应式数据
const record = ref<any>(null)
const exam = ref<any>(null)
const answers = ref<any[]>([])

// 计算属性
const canRetake = computed(() => {
  if (!record.value || !exam.value) return false
  return record.value.attemptNumber < (exam.value?.maxAttempts || 1)
})

const correctRate = computed(() => {
  const score = Number(record.value?.totalScore || 0)
  const total = Number(record.value?.totalPoints || 0)
  if (!total) return 0
  return Math.round((score / total) * 100)
})

// 方法
const loadExamResult = async () => {
  try {
    const [recordRes, answersRes] = await Promise.all([
      examApi.getRecord(recordId),
      examApi.getAnswers(recordId)
    ])
    record.value = recordRes
    answers.value = answersRes
    // 取考试信息（标题、及格线、是否显示正确答案等）
    if (record.value?.examId) {
      exam.value = await examApi.get(record.value.examId)
    }
  } catch (error) {
    console.error('加载考试结果失败:', error)
    ElMessage.error(getErrorMessage(error))
    router.back()
  }
}

const formatDuration = (seconds: number) => {
  if (!seconds) return '0分钟'
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return minutes > 0 ? `${minutes}分${remainingSeconds}秒` : `${remainingSeconds}秒`
}

const formatAnswer = (answer: any, questionType: string, options?: any[]) => {
  if (!answer) return '未作答'
  
  if (questionType === 'TRUE_FALSE') {
    return answer === 'true' || answer === true ? '正确' : '错误'
  }
  
  if (['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(questionType) && options) {
    const indices = Array.isArray(answer) ? answer : [answer]
    return indices.map((index: any) => {
      // 处理字母索引（A, B, C, D）
      if (typeof index === 'string' && index.match(/^[A-Z]$/)) {
        const numIndex = index.charCodeAt(0) - 65
        return options[numIndex]?.content || index
      }
      // 处理数字索引
      const numIndex = Number(index)
      if (!isNaN(numIndex) && numIndex >= 0 && numIndex < options.length) {
        return options[numIndex]?.content || String(index)
      }
      return String(index)
    }).join(', ')
  }
  
  return String(answer)
}

const goBack = () => {
  if (record.value?.exam?.courseId) {
    router.push(`/courses/${record.value.exam.courseId}`)
  } else {
    router.back()
  }
}

const retakeExam = () => {
  if (exam.value?.id) {
    router.push(`/exam/${exam.value.id}`)
  }
}

const goToCertificates = () => {
  router.push('/my-certificates')
}

// 生命周期
onMounted(() => {
  loadExamResult()
})
</script>

<style scoped>
.exam-result-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.result-overview { background:#fff; border-radius:12px; box-shadow:0 4px 12px rgba(0,0,0,0.08); padding: 24px; margin-bottom: 16px; }

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.result-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 20px;
}

.stat-item { text-align:center; padding:14px; background:#f6f9ff; border:1px solid #e6eefb; border-radius:10px; }
.stat-item.big { background:#fff; border:1px solid #e6eefb; border-radius:12px; box-shadow:0 4px 12px rgba(0,0,0,0.06); }
.radial { transform: rotate(-90deg); display:block; margin: 0 auto 6px; }
.bg { fill:none; stroke:#eef2ff; stroke-width:4; }
.bar { fill:none; stroke-width:4; stroke-linecap:round; }
.bar.good { stroke:#1ea97c; }
.bar.pass { stroke:#1865f2; }
.bar.fail { stroke:#e34d59; }
text.label { transform: rotate(90deg); transform-origin: 18px 18px; font-size: 8px; text-anchor: middle; dominant-baseline: middle; fill: #0f172a; font-weight: 700; }

.stat-value { font-size:24px; font-weight:700; color:#1865f2; margin-bottom:4px; }

.stat-label { color:#64748b; font-size:12px; }

.answer-details { background:#fff; border-radius:12px; box-shadow:0 4px 12px rgba(0,0,0,0.08); padding:24px; margin-bottom:16px; }

.answer-details h3 {
  margin-bottom: 20px;
  color: #333;
}

.answer-item {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.answer-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.question-number {
  font-weight: bold;
  color: #333;
}

.question-meta {
  display: flex;
  gap: 10px;
}

.question-content {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 15px;
  line-height: 1.6;
}

.answer-content > div {
  margin-bottom: 10px;
}

.correct {
  color: #67c23a;
  font-weight: bold;
}

.incorrect {
  color: #f56c6c;
  font-weight: bold;
}

.explanation {
  background: #e1f3d8;
  padding: 12px;
  border-radius: 6px;
  border-left: 4px solid #67c23a;
}

.explanation p {
  margin: 0;
  color: #333;
}

.certificate-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
  padding: 30px;
  text-align: center;
  margin-bottom: 20px;
}

.certificate-icon {
  font-size: 48px;
  color: #ffd700;
  margin-bottom: 15px;
}

.certificate-section h3 {
  margin-bottom: 10px;
  color: white;
}

.certificate-section p {
  margin-bottom: 20px;
  opacity: 0.9;
}

.result-actions {
  text-align: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.result-actions .el-button {
  margin: 0 10px;
  padding: 12px 24px;
}
</style>